import { createRouter, createWebHistory } from 'vue-router'
import PkIndexView from '../views/pk/PkIndexView.vue'
import RecordIndexView from '../views/record/RecordIndexView.vue'
import RanklistIndexView from '../views/ranklist/RanklistIndexView.vue'
import UserBotIndexView from '../views/user/bot/UserBotIndexView.vue'
import NotFound from '../views/error/NotFound.vue'
import UserAccountLoginView from '../views/user/account/UserAccountLoginView.vue'
import UserAccountRegisterView from '../views/user/account/UserAccountRegisterView.vue'
import store from '../store/index.js'
const routes = [
  {  //只有根路径的话,重定向到pk路径
    path:'/', 
    name: 'home',
    redirect: '/pk/',
    meta:{
      requestAuth: true, //需要授权（登录后才能进入）
    }
  },
  {
    path:'/user/account/login/',
    name: 'user_account_login',
    component: UserAccountLoginView,
    meta:{
      requestAuth: false, 
    }
  },
  {
    path:'/user/account/register/',
    name: 'user_account_register',
    component: UserAccountRegisterView,
    meta:{
      requestAuth: false, 
    }
  },
  {
    path:'/pk/',
    name: 'pk_index',
    component: PkIndexView,
    meta:{
      requestAuth: true, 
    }
  },
  {
    path:'/record/',
    name: 'record_index',
    component: RecordIndexView,
    meta:{
      requestAuth: true, 
    }
  },
  {
    path:'/ranklist/',
    name: 'ranklist_index',
    component: RanklistIndexView,
    meta:{
      requestAuth: true, 
    }
  },
  {
    path:'/user/bot/',
    name: 'user_bot_index',
    component: UserBotIndexView,
    meta:{
      requestAuth: true, 
    }
  },
  {
    path:'/404/',
    name: 'not_found',
    component: NotFound,
    meta:{
      requestAuth: false, 
    }
  },
  {//所有路径都没有匹配到的话,重定向到404路径（路径是从上往下匹配的）
    path:'/:catchAll(.*)',
    redirect: '/404/',
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})
//通过router跳转到每个页面之前，执行这个函数 （to:要跳转到的页面，from:从哪个页面跳转，next:要不要执行下一步操作）
router.beforeEach((to,from,next) => { 
  if(to.meta.requestAuth && !store.state.user.is_login){ //需要授权并且未登录
    next({name:"user_account_login"}); //跳转到登录页面
  }else{
    next(); //执行默认操作
  }
})

export default router
